package nettyguide;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;

/**
 * 创建自定义助手类
 * @author Shensg
 *
 * 2019年6月18日
 */
//SimpleChannelInboundHandler: 对于请求来讲,相当于入站
public class CustomHandler extends SimpleChannelInboundHandler<HttpObject> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) 
			throws Exception {
		
		//获取channel
		Channel channel = ctx.channel();
		//校验是否是HTTP请求
		if (msg instanceof HttpRequest) {
			//显示客户端地址
			System.out.println(channel.remoteAddress());
		}
		//定义发送数据
		ByteBuf content = Unpooled.copiedBuffer("Hello Netty 嘻嘻 ~",CharsetUtil.UTF_8);
		//构建http response
		FullHttpResponse response =
				new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
						HttpResponseStatus.OK,
						content);
		//设置数据类型
		response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=UTF-8");
		//文本长度
		response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());
		
		//把响应发送到客户端
		ctx.writeAndFlush(response);
	}

}
